package com.aids_malaria.ui.setting;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.RoleManagerAuthAdapter;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.request.SaveRoleRequest;
import com.aids_malaria.http.response.Role;
import com.aids_malaria.http.response.RoleAuth;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;

import org.w3c.dom.ls.LSInput;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class RoleManagerCreateEditActivity extends BaseActivity implements RoleManagerAuthAdapter.Option{

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.rv_role_auth)
    RecyclerView rv_role_auth;
    @BindView(R.id.et_role_name)
    EditText et_role_name;
    @BindView(R.id.et_function_name)
    EditText et_function_name;
    @BindView(R.id.cb_check_all)
    CheckBox cb_check_all;

    public static final String KEY_IS_CREATE = "is_create";
    public static final String KEY_ROLE = "role";

    private boolean isCreate;
    private Role mRole;

    private List<RoleAuth> mData = new ArrayList<>();
    private List<RoleAuth> mOriginalData = new ArrayList<>();
    private RoleManagerAuthAdapter roleManagerAuthAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_role_manager_create_edit;
    }

    @Override
    protected void initView() {
        super.initView();
        et_function_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String inputStr = charSequence.toString();
                mData.clear();
                for(int j=0; j<mOriginalData.size(); j++){
                    if(mOriginalData.get(j).getFunc_name().contains(inputStr)){
                        mData.add(mOriginalData.get(j));
                    }
                }
                roleManagerAuthAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        if(null != bundle){
            isCreate = bundle.getBoolean(KEY_IS_CREATE);
        }
        if(isCreate){
            initTitleBar(title_bar,getString(R.string.role_create));
            mRole = new Role();
            mRole.setRole_id("");
            mRole.setRole_name("");
            mRole.setCreator("");
            mRole.setCreating_time("");
            mRole.setUpdator("");
            mRole.setUpdate_time("");
            getNewRoleAuth();
        }else{
            initTitleBar(title_bar,getString(R.string.role_edit));
            et_role_name.setEnabled(false);
            et_role_name.setBackground(getResources().getDrawable(R.drawable.shape_rounded_gray));
            mRole = (Role) bundle.getSerializable(KEY_ROLE);
            et_role_name.setText(mRole.getRole_name());
            getRoleAuth(mRole.getRole_id());
        }
        initRecycleView();
    }

    private void initRecycleView() {
        rv_role_auth.setLayoutManager(new LinearLayoutManager(mContext));
        roleManagerAuthAdapter = new RoleManagerAuthAdapter(mContext,R.layout.item_role_manager_auth,mData,this);
        rv_role_auth.setAdapter(roleManagerAuthAdapter);
        roleManagerAuthAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });

        cb_check_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = cb_check_all.isChecked();
                for (int i=0; i<mData.size(); i++){
                    mData.get(i).setCheck(checked);
                    roleManagerAuthAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @OnClick({R.id.tv_confirm,R.id.cb_check_all})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_confirm:
                String roleName = et_role_name.getText().toString().trim();
                if(StringUtil.isEmpty(roleName)){
                    ToastUtil.showToast(getString(R.string.input_null));
                    return;
                }
                mRole.setRole_name(roleName);
                String busy_type_auth = "";
                ArrayList<RoleAuth> list = new ArrayList<>();
                if(isCreate){
                    for (int i=0; i<mData.size(); i++){
                        RoleAuth roleAuth = mData.get(i);
                        if (roleAuth.getCheck()){
                            busy_type_auth = busy_type_auth + "1";

                            list.add(roleAuth);
                            LogUtil.d("roleName:------------" + roleAuth.getFunc_name());
                        }
                    }
                    LogUtil.d("busy_type_auth:------------" + busy_type_auth);
                    saveRole("1",mRole,busy_type_auth,list,null);
                }else{
                    for (int i=0; i<mData.size(); i++){
                        RoleAuth roleAuth = mData.get(i);
                        if (roleAuth.getCheck()){
                            busy_type_auth = busy_type_auth + "2";
                            roleAuth.setUpdate(1);
                            roleAuth.setDelete(1);
                            roleAuth.setInsert(1);
                            roleAuth.setInq(1);
                            roleAuth.setDownload(1);
                            roleAuth.setUpload(1);
                            list.add(roleAuth);
                            LogUtil.d("roleName:------------" + roleAuth.getFunc_name());
                        }

                    }
                    LogUtil.d("busy_type_auth:------------" + busy_type_auth);
                    saveRole("2",mRole,busy_type_auth,mData,null);
                }
                break;


        }
    }



    /**
     * 获取角色权限数据
     *
     */
    private void getRoleAuth(String roleId) {
        String funcName = et_function_name.getText().toString().trim();
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getRoleAuth(roleId, funcName)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<RoleAuth>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<RoleAuth> data) throws Exception {
                        mData.clear();
                        mData.addAll(data);
                        mOriginalData.clear();
                        mOriginalData.addAll(data);
                        roleManagerAuthAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 获取新角色权限数据
     *
     */
    private void getNewRoleAuth() {
        String funcName = et_function_name.getText().toString().trim();
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getNewRoleAuth(funcName)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<RoleAuth>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<RoleAuth> data) throws Exception {
                        mData.clear();
                        mData.addAll(data);
                        mOriginalData.clear();
                        mOriginalData.addAll(data);
                        roleManagerAuthAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 保存新角色权限数据
     * @param busy_type  角色保存类型 1插入 2更改 3 删除
     * @param role_data  (各数据字段定义见数据库表TBL_COM_ROLE定义) 该角色数据 (json格式)
     * @param busy_type_auth  角色权限数据保存类型，1插入 2更改 3 删除，位串，权限数据有多少条就有几位
     * @param role_auth_data  (各数据字段定义见数据库表TBL_COM_ROLE_AUTH定义)：角色权限数据（多条）
     * @return
     */
    private void saveRole(String busy_type, Role role_data, String busy_type_auth,List<RoleAuth> role_auth_data,RoleAuth roleAuth) {
        SaveRoleRequest saveRoleRequest = new SaveRoleRequest();
        saveRoleRequest.setRole_data(role_data);
        saveRoleRequest.setRole_auth_data(role_auth_data);
        LogUtil.d("saveRoleRequest:"+GsonUtil.beanToJson(saveRoleRequest));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.beanToJson(saveRoleRequest));
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).saveRole(busy_type,busy_type_auth,requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(ResourceUtil.getString(R.string.operate_success));
                        cb_check_all.setChecked(false);
                        if (!isCreate){
                            ArrayList<RoleAuth> list = new ArrayList();
                            list.addAll(mData);
                            mData.clear();
                            for (int i = 0; i < list.size(); i++) {
                                RoleAuth obj = list.get(i);
                                if (obj.getFunc_code().equals(roleAuth.getFunc_code())){
                                    mData.add(roleAuth);
                                }else{
                                    mData.add(obj);
                                }
                            }

                            ArrayList<RoleAuth> orglist = new ArrayList();
                            orglist.addAll(mOriginalData);
                            mOriginalData.clear();
                            for (int i = 0; i < orglist.size(); i++) {
                                RoleAuth obj = orglist.get(i);
                                if (obj.getFunc_code().equals(roleAuth.getFunc_code())){
                                    mOriginalData.add(roleAuth);
                                }else{
                                    mOriginalData.add(obj);
                                }

                            }
                            roleManagerAuthAdapter.notifyDataSetChanged();
                            return;
                        }

                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }
    @Override
    public void onItemCheck(int position, boolean isCheck) {
        mData.get(position).setCheck(isCheck);
        int totalselect = 0;
        for (int i = 0; i < mData.size() ; i++) {
            if (mData.get(i).getCheck()){
                totalselect++;
            }
        }
        if (totalselect < mData.size() ){
            cb_check_all.setChecked(false);
        }
    }

    @Override
    public void createClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setInsert(roleAuth.getInsert() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

    @Override
    public void deleteClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setDelete(roleAuth.getDelete() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

    @Override
    public void editClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setUpdate(roleAuth.getUpdate() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

    @Override
    public void downloadClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setDownload(roleAuth.getDownload() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

    @Override
    public void uploadClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setUpload(roleAuth.getUpload() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

    @Override
    public void queryClick(int position) {
        if (isCreate)return;
        RoleAuth roleAuth = mData.get(position);
        roleAuth.setInq(roleAuth.getInq() == 1 ? 0 : 1);
        ArrayList arrayList = new ArrayList();
        arrayList.add(roleAuth);
        saveRole("2",mRole,"2",arrayList,roleAuth);
    }

}
